from math import ceil
import numpy as np
import wave


def signal(t):
    freq = 1e3
    return 0.5 + np.sin(2 * np.pi * freq * t)


f_sample = 44.1e3
n_channel = 1
sample_width = 2  # 单位: byte

t_total = 20
n_frame = ceil(t_total * f_sample) + 1
t_start = 0
t_end = n_frame / f_sample + t_start
t = np.linspace(t_start, t_end, num=n_frame, endpoint=True)
wave_data = signal(t)
wave_data = wave_data - wave_data.min()
wave_data /= wave_data.max()
wave_data = (wave_data * (2 ** 15 - 1)).astype(np.int16)

f = wave.open("sin_1kHz.mp3", 'w')
f.setnchannels(n_channel)
f.setsampwidth(sample_width)
f.setframerate(f_sample)
comptype = "NONE"
compname = "not compressed"

f.writeframes(wave_data.tobytes())
f.close()
